// pages/index/index.js
import {
    baseUrl
} from "../../static/url"
import {
    httpRequest
} from "../../utils/request"
Page({

    /**
     * 页面的初始数据
     */
    data: {
        current: 1,
        autoplay: true,
        duration: 500,
        interval: 5000,
        swiperList: [
            `/static/image/banner.png`,
        ],
        subfiles: [],
        text: "极易检修单",
        autosize: {
            maxHeight: 120,
            minHeight: 20,
        },
        originFiles: [
        ],
        gridConfig: {
            column: 4,
            width: 160,
            height: 160,
        },
        config: {
            count: 1,
        },
        form: {
            name: "",
            address: "",
            remark: "",
            lonlat: "",
        },
        style: '',
    },
    onLineChange(e) {
        console.log(e)
        console.log('lineCount: ', e.detail);
    },
    createRepair() {
        // httpRequest("1", "2", "#")
        let that = this
        let data = this.data.form
        // 检查表单是否完整
        for(let k in data){
            let v = data[k]
            if(!v){
                console.log(k)
                wx.showModal({
                    title: '提示',
                    content: '单据未填写完或未选择位置',
                })
                return false
            }
        }
        // 检查是否上传图片
        if(this.data.subfiles.length  < 1){
            wx.showModal({
                title: '提示',
                content: '至少上传一张问题图片',
            })
            return false
        }
        // 开始上传
        wx.showLoading({
          title: '正在生成',
        })
        data.files = this.data.subfiles
        data.originfiles = this.data.originFiles

        httpRequest("repair/bill/create", 'POST', data).then(r => {
            if(r.code == 200){
                that.setData({
                    form : {
                      name: "",
                      address: "",
                      remark: "",
                      lonlat: "",
                    }
                })
                wx.showModal({
                  title: '提示',
                  content: '检修单生成成功,前往检修单模块分享单据',
                  complete: (res) => {
                      wx.switchTab({
                        url: '/pages/bill/bill',
                      })
                  }
                })
            }else{
                wx.showModal({
                  title: '提示',
                  content: r.msg,
                })
            }
        })
        console.log(this.data.subfiles)
    },
    // 上传文件相关函数===开始
    uploadimg(e) {
        console.log(e)
    },
    handleFail(e){
        if(e.detail.errMsg == 'chooseMedia:fail cancel'){
            return false
        }
        const {
            originFiles
        } = this.data;
        const {
            length
        } = originFiles;
        this.setData({
            [`originFiles[${length}].status`]: 'fail',
        });
    },
    handleAdd(e) {
        // const { originFiles } = this.data;
        const {
            files
        } = e.detail;

        // 方法1：选择完所有图片之后，统一上传，因此选择完就直接展示
        // this.setData({
        //     originFiles: [...originFiles, ...files], // 此时设置了 fileList 之后才会展示选择的图片
        // });

        // 方法2：每次选择图片都上传，展示每次上传图片的进度
        files.forEach(file => this.onUpload(file))
    },
    onUpload(file) {
        console.log(file)
        let self = this

        var token = wx.getStorageSync('token')
        if (!token) {
            wx.showToast({
                title: '请先登录',
                icon: "none"
            })
            setTimeout((

            ) => {
                wx.navigateTo({
                    url: '/pages/login/login',
                })
            }, 800)
            return false
        }
        const {
            originFiles
        } = this.data;
        this.setData({
            originFiles: [...originFiles, {
                ...file,
                status: 'loading'
            }],
        });
        const {
            length
        } = originFiles;
        const task = wx.uploadFile({
            url: baseUrl + '/api/upload/upload?HTTP_TOKENs=' + token, // 
            filePath: file.url,
            name: 'file',
            formData: {
                user: 'test'
            },
            success: (r) => {
                if(r.statusCode != 200){
                    wx.showToast({
                      title: '上传失败,未知原因',
                      icon : "error"
                    })
                    self.setData({
                        [`originFiles[${length}].status`]: 'fail',
                    });
                    return false
                }
                console.log(r)
                let data = JSON.parse(r.data)
                let subfiles = self.data.subfiles
                subfiles.push(data.data.file_name)
                self.setData({
                    subfiles: subfiles,
                    [`originFiles[${length}].status`]: 'done',
                });
            },
            fail() {
                self.setData({
                    [`originFiles[${length}].status`]: 'fail',
                });
            }
        });
        task.onProgressUpdate((res) => {
            self.setData({
                [`originFiles[${length}].percent`]: res.progress,
            });
        });
    },
    handleSuccess(e) {
        const {
            files
        } = e.detail;
        // this.setData({
        //   originFiles: files,
        // });
    },
    handleRemove(e) {
        const {
            index
        } = e.detail;
        const {
            originFiles,
            subfiles
        } = this.data;
        originFiles.splice(index, 1);
        subfiles.splice(index, 1);
        this.setData({
            originFiles,
            subfiles
        });
    },
    handleClick(e) {
        console.log(e.detail.file);
    },
    chooseAddress() {
        let that = this
        wx.chooseLocation({
            success: (result) => {
                that.setData({
                    'form.detailaddress': result.address ? result.address : result.longitude + ',' + result.latitude,
                    'form.address': result.name ? result.name : result.longitude + ',' + result.latitude,
                    'form.lonlat': result.longitude + ',' + result.latitude,
                })
                console.log(result)
            },
            fail: (res) => {},
            complete: (res) => {},
        })
    },
    // 上传文件相关函数===结束
    // 输入框==开始
    inputchange(e) {
        let form = this.data.form
        form[e.currentTarget.dataset.field] = e.detail.value
        this.setData({
            form
        });
    },
    // 输入框==结束
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
        return {
            title: '极易检修单',
            path: '/pages/index/index',
            imageUrl: '/static/image/banner.png'
          }
    }
})